<template>
  <el-container class="app_container flex">
    <Aside @handleNodeClick="handleNodeClick" />
    <el-main class="app_main flex">
      <Breadcrumb :title="pageTitle" />
      <div class="app_content">
        <el-form ref="searchForm" :model="searchMap">
          <el-row class="flex serach_item">
            <el-button v-for="item in alarmType" type="primary" :key="item.type" :class="currentAlarmType === item.type ? 'btn_group_active' : 'btn_group'" @click="clickAlarmType(item.type)">
              {{ item.label }}（{{ item.sum }}）
            </el-button>
          </el-row>
          <el-form-item label="报警等级:" class="serach_item">
            <el-row class="flex">
              <el-button v-for="item in exigency" type="primary" :key="item.value" :class="currentExigency === item.value ? 'btn_group_active' : 'btn_group'" @click="clickExigency(item.value)">
                {{ item.label }}（{{ item.sum }}）
              </el-button>
            </el-row>
          </el-form-item>
          <el-row :gutter="4">
            <el-col :span="3">
              <el-form-item prop="alarmReason" size="small">
                <el-input v-model="searchMap.alarmReason" placeholder="报警原因"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item prop="userName" size="small">
                <el-date-picker v-model="currentTime" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" @change="changeDate">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-form-item prop="deviceStatus" size="small">
                <el-select v-model="searchMap.deviceTypeId" placeholder="请选择报警归属设备" clearable filterable>
                  <el-option v-for="item in deviceTypeList" :key="item.deviceTypeId" :label="item.deviceTypeName" :value="item.deviceTypeId" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-form-item prop="deviceStatus" size="small">
                <!-- <el-select v-model="searchMap.alarmEventTypeId" placeholder="报警类型名称" clearable>
                  <el-option v-for="item in alarmEventTypelist" :key="item.alarmEventTypeId" :label="item.eventAlarmDescribe" :value="item.alarmEventTypeId" />
                </el-select> -->
                <!-- <el-tree :data="alarmEventTypelist" show-checkbox node-key="id" :default-expanded-keys="[2, 3]" :default-checked-keys="[5]" :props="defaultProps">
                </el-tree> -->

                <!-- <el-select v-model="searchMap.alarmEventTypeId" placeholder="请选择报警类型名称" clearable filterable>
                  <el-option-group v-for="group in alarmEventTypelist" :key="group.label" :label="group.label">
                    <el-option v-for="item in group.options" :key="item.alarmEventTypeId" :label="item.label" :value="item.alarmEventTypeId">
                    </el-option>
                  </el-option-group>
                </el-select> -->

                <el-cascader placeholder="请选择报警类型名称" :options="alarmEventTypelist" @change="handleChange" :props="{value: 'alarmEventTypeId'}" clearable filterable></el-cascader>

              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-form-item class="flex">
                <el-button @click="getList" class="btn_primary" style="margin-right=10px;">
                  查询
                </el-button>
                <el-button @click="handleReset()" class="btn_cancel">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-table :data="alarmList" stripe class="per_table" style="width: 100%" height="550" v-loading="alarmLoading">
          <el-table-column type="index" label="序号" header-align="center" align="center" width="80">
          </el-table-column>
          <el-table-column prop="alarmNo" label="报警编号" align="center"></el-table-column>
          <el-table-column prop="deviceName" label="设备名称" align="center"></el-table-column>
          <el-table-column prop="threshold" label="阈值" align="center"></el-table-column>
          <el-table-column prop="alarmUrgency" label="报警等级" align="center" width="80">
            <template slot-scope="scope">
              <div class="flex flex-bcenter">
                <span class="urency-tag" :class="formatUrgency(scope.row.alarmUrgency)"></span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="projectPointName" label="所属点位" align="center"></el-table-column>
          <el-table-column prop="createTime" label="报警时间" align="center"></el-table-column>
          <el-table-column prop="updateTime" label="最新时间" align="center"></el-table-column>
          <el-table-column prop="installPosition" label="报警位置" align="center"></el-table-column>
          <el-table-column prop="categoryName" label="报警类型" align="center"></el-table-column>
          <el-table-column prop="eventName" label="报警事件" align="center"></el-table-column>
          <el-table-column prop="alarmReason" label="报警原因" align="center" width="350"></el-table-column>
          <el-table-column key="alarmStatus" label="状态" align="center">
            <template slot-scope="scope">
              <div class="status-content" v-if="scope.row.alarmStatus == 0">
                <span class="status-unusual-radius"></span>
                <span class="status-unusual">待处理</span>
              </div>
              <div class="status-content" v-else-if="scope.row.alarmStatus == 5">
                <span class="status-normal-radius"></span>
                <span class="status-normal">已完成</span>
              </div>
              <div class="status-content" v-else>
                <span class="status-warning-radius"></span>
                <span class="status-warning">处理中</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="300" align="center">
            <template slot-scope="scope">
              <span type="text" class="tag_primary" size="small" @click="handleAlarm(scope.row)">报警处理</span>
              <!-- <span type="text" class="tag_warning" size="small" @click="handleEmergency(scope.row)">应急处理</span> -->
            </template>
          </el-table-column>
        </el-table>
        <pagination :total="total" :page.sync="searchMap.pageNum" :limit.sync="searchMap.pageSize" @change="getList" />
      </div>
    </el-main>
    <el-dialog title="报警处理" class="large_dialog" :visible.sync="dialogDetails" top="10px" append-to-body>
      <!-- <alarm-details :alarmDetails="alarmDetails" @repace="getList"></alarm-details> -->
      <alarm-dialog :details="alarmDetails" @repace="getList"></alarm-dialog>
    </el-dialog>
    <el-dialog title="应急处理" class="large_dialog" :visible.sync="dialogVisableEmergency" top="10px">
      <emergency :details="alarmDetails" @repace="getList"></emergency>
    </el-dialog>
  </el-container>
</template>
<script>

import { listDeviceTypesData } from '@/api/system/device/types';
import Aside from '@/components/Aside'
import { EventBus } from '@/utils/eventbus'
import { listAlarm, statCount, categoryNameDataList } from '@/api'
import AlarmDialog from './components/AlarmDialog'
import Emergency from './components/Emergency'

export default {
  name: 'alarm',
  dicts: ['alarm_urgency_status'],
  data() {
    return {
      // 报警列表
      alarmList: ['alarm_urgency_status'],
      total: 0,
      alarmLoading: true,
      searchMap: {
        pageNum: 1,
        pageSize: 10,
        alarmStatus: undefined,
        deptId: 0,
        keyword: '',
        endTime: '',
        startTime: '',
        deviceTypeId: ''
      },
      alarmType: [
        {
          label: '全部',
          type: undefined,
          filedValue: 'all',
        },
        {
          label: '待处理',
          type: '0',
          filedValue: 'todoCount',
        },
        {
          label: '处理中',
          type: '-1',
          filedValue: 'processingCount',
        },
        {
          label: '已处理',
          type: '5',
          filedValue: 'processedCount',
        },
      ],
      // 当前报警类型
      currentAlarmType: undefined,
      // 紧急度
      exigency: [
        // {
        //   label: '全部',
        //   type: undefined,
        //   filedValue: 'all'
        // },
        // {
        //   label: '高',
        //   type: '1',
        //   filedValue: 'highCount'
        // },
        // {
        //   label: '中',
        //   type: '2',
        //   filedValue: 'middleCount'
        // },
        // {
        //   label: '低',
        //   type: '3',
        //   filedValue: 'lowCount'
        // },
      ],
      // 当前
      currentExigency: undefined,
      dialogDetails: false,
      alarmDetails: {},
      // 应急处理弹框
      dialogVisableEmergency: false,
      //选择时间
      currentTime: '',
      // 设备类型列表
      deviceTypeList: [],
      // 报警类型名称列表
      alarmEventTypelist: [],

      defaultProps: {
        children: 'children',
        label: 'label'
      }
    }
  },
  computed: {
    pageTitle() {
      return '报警管理'
    },
  },
  watch: {
    numResult(newVal) {
      if (newVal !== undefined) {
        this.compututeNumResult
      }
    },
  },
  created() {
    EventBus.$on('currentTree', (data) => {
      this.searchMap.deptId = data.id

      this.getListDeviceTypesData()
      this.getCategoryNameDataList()
      this.getList()
    })
  },
  mounted() {
    // this.tree()
  },
  methods: {
    // 获取报警列表
    async getList() {
      this.alarmLoading = true
      const listAlarmVal = listAlarm(this.searchMap)
      const listStatCount = statCount(this.searchMap)
      let listData = await Promise.all([listAlarmVal, listStatCount])
      this.calculSum(listData[1])
      this.total = listData[0].total
      this.alarmList = listData[0].rows
      this.alarmLoading = false
    },
    // 计算紧急度和报警列表数量
    calculSum(count) {
      if (count.code === 200) {
        for (let key in count.data) {
          this.calcuSumCount(count.data[key], key)
        }
      }
    },
    // 计算紧急度和报警列表总数
    calcuSumCount(data, key) {
      const sumCount = Object.values(data).reduce((accumulator, currentValue) => accumulator + currentValue, 0)
      if (key === 'numResult') {
        for (let i = 0; i < this.alarmType.length; i++) {
          if (this.alarmType[i].filedValue === 'all') {
            this.alarmType[i].sum = sumCount
          } else {
            for (let key in data) {
              if (this.alarmType[i].filedValue === key) {
                this.alarmType[i].sum = data[key]
              }
            }
          }
        }
      } else {
        let exigency = this.exigency = [{
          label: "全部",
          value: '',
          type: 'all'
        }].concat(this.dict.type.alarm_urgency_status.map(item => {
          switch (item.value) {
            // 重大
            case '1':
              item.type = 'highCount'
              break;
            // 较大
            case '2':
              item.type = 'middleCount'
              break;
            // 一般
            case '3':
              item.type = 'lowCount'
              break;
            // 低
            case '4':
              item.type = 'lowestCount'
              break;
          }
          return item
        }))
        for (let i = 0; i < exigency.length; i++) {
          if (exigency[i].type === 'all') {
            exigency[i].sum = sumCount
          } else {
            for (let key in data) {
              if (exigency[i].type === key) {
                exigency[i].sum = data[key]
              }
            }
          }
        }
      }
    },
    changeDate(date) {
      this.searchMap.startTime = date[0]
      this.searchMap.endTime = date[1]
    },
    // 根据状态渲染对应标签
    formatUrgency(value) {
      let typeStyle = ''
      switch (value) {
        case '1':
          typeStyle = 'high'
          break
        case '2':
          typeStyle = 'center'
          break
        case '3':
          typeStyle = 'low'
          break
        case '3':
          typeStyle = 'lowest'
          break
      }
      return typeStyle
    },
    handleReset() {
      this.searchMap = {
        pageNum: 1,
        pageSize: 10,
        alarmStatus: undefined,
        deptId: 0,
        keyword: '',
        endTime: '',
        startTime: '',
      }
      this.currentTime = ''
      this.getList()
    },
    /** 点击报警状态 */
    clickAlarmType(type) {
      this.currentAlarmType = type
      this.searchMap.alarmStatus = type
      this.getList()
    },
    /** 点击紧急度状态 */
    clickExigency(value) {
      this.currentExigency = value
      this.searchMap.alarmUrgency = value
      this.getList()
    },
    // 点击报警处理
    handleAlarm(row) {
      this.alarmDetails = row
      this.dialogDetails = true
    },
    // 点击应急处理
    handleEmergency(row) {
      this.alarmDetails = row
      this.$router.push({ path: 'Emergency', query: { alarmId: row.alarmId } })
    },
    // 树形菜单点击
    handleNodeClick(item) {
      this.searchMap.deptId = item.id
      this.getList()
    },
    // 获取 报警归属设备（设备类型）
    async getListDeviceTypesData() {
      await listDeviceTypesData({ pid: '1813058523583492098' }).then(res => {
        if (res && 200 == res.code) {
          this.deviceTypeList = res.data
        }
      })
    },
    // 查询告警事件类型按一级分类返回对应的列表
    async getCategoryNameDataList() {
      await categoryNameDataList().then(res => {
        if (res) {
          // this.alarmEventTypelist = res
          let temp = []
          for (let p in res) {
            let arr = res[p].map(item => {
              item.label = item.eventName
              return item
            })

            temp.push({
              label: p,
              children: arr
            })
          }
          this.alarmEventTypelist = temp
        }
      })
    },
    handleChange(value) {
      console.log(value);
      this.searchMap.alarmEventTypeId = value[1]
    }
  },
  beforeDestroy() {
    EventBus.$off('currentTree')
  },
  components: {
    Aside,
    AlarmDialog,
    Emergency
  },
}
</script>

<style lang="less">
.serach_item {
  margin-bottom: 15px;
}

.app_content {
  .per_table {
    margin-bottom: 15px;

    .high {
      background: url("@/assets/images/alarm/high.png") no-repeat center;
    }

    .center {
      background: url("@/assets/images/alarm/center.png") no-repeat center;
    }

    .low {
      background: url("@/assets/images/alarm/lower.png") no-repeat center;
    }

    .lowest {
      background: url("@/assets/images/alarm/lowest.png") no-repeat center;
    }
  }
}
</style>
